<?php
// 应用公共文件
function setPassword($password, $token = null): array
{
    if (empty($token)) $token = \think\helper\Str::random(16, 6);
    return [
        "password" => password_hash($token . $password . $token, PASSWORD_DEFAULT),
        "token" => $token
    ];
}

function checkPassword($password, $hash, $token): bool
{
    return password_verify($token . $password . $token, $hash);
}

function pageData($data): array
{
    return [
        "data" => $data['data'],
        "last_page" => $data['last_page'],
        "total" => $data['total']
    ];
}

function sendSms($tpl, $mobile, $message, $signature = "成都富海天下"): bool
{
    $sms = new \zt_sms\ZtSms();
    $items = $sms->init()->setBiz("/v2/sendSmsTp")->setData([
        "signature" => "【{$signature}】",
        "tpId" => $tpl,
        "records" => [
            [
                "mobile" => $mobile,
                "tpContent" => $message
            ]
        ]
    ])->send();
    return !empty($items) && strtolower($items['msg']) == "success";
}

function matchDiscount($default, $priceConf)
{
    //计算优惠单价
    $initMoney = 0;
    if (!empty($priceConf)) {
        switch ((int)$priceConf['rule']) {
            case 1:
                $initMoney = (float)$priceConf['number'];
                break;
            default:
                $num = (float)bcdiv($priceConf['number'], 100, 4);
                $number = (float)bcmul($default['price'], $num, 4);
                $initMoney = match ($priceConf['rule']) {
                    3 => bcdiv(ceil($number * 100), 100, 2),
                    4 => bcdiv(floor($number * 100), 100, 2),
                    default => round($num, 2)
                };
                break;
        }
        $initMoney = (float)$priceConf['price_unit'] == 2 ? bcsub($default['price'], $initMoney, 2) : bcadd($default['price'], $initMoney, 2);
    }

    return $initMoney;
}

function excel($data): array
{
    return [
        "result" => $data['result'] ?? [],
        "last_page" => $data['last_page'] ?? 1,
        "file" => $data['file'] ?? "导出文件",
        "title" => $data['title'] ?? "导出文件",
        "header" => $data['header'] ?? [],
        "merge" => $data['merge'] ?? []
    ];
}
